package com.web.rate.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.web.common.BaseResult;
import com.web.common.enums.BaseStatus;
import com.web.rate.entity.Rate;
import com.web.rate.service.RateService;
import com.web.systemParam.entity.SystemParam;
import com.web.systemParam.service.SystemParamService;
import com.web.transaction.entity.Transaction;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sound.midi.Soundbank;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "API - RateController",description = "rate")
@RestController
@CrossOrigin
@RequestMapping("/rate")
public class RateController {

    @Autowired
    private RateService rateService;

    @Autowired
    private SystemParamService systemParamService;

    private static final Logger logger = LoggerFactory.getLogger(RateController.class);

    @RequestMapping(value = "/rateList")
    public BaseResult<List<Rate>> rateList(@ModelAttribute Rate rate){
    	List<Rate> rateList = rateService.getRates(rate);
    	return new BaseResult<>(BaseStatus.SUCCESS.getCode(),rateList);
    }


    @RequestMapping(value = "/getRate")
    public BaseResult<BigDecimal> getRate(@RequestParam("buyCurrency") String buyCurrency, @RequestParam("sellCurrency") String sellCurrency){

        Rate buyRate = rateService.getRate(buyCurrency, Transaction.TX_BUY);

        Rate sellRate = rateService.getRate(sellCurrency, Transaction.TX_SELL);

        BigDecimal result = BigDecimal.ZERO;

        if(buyRate.getRate().compareTo(sellRate.getRate()) > 0){
             result = buyRate.getRate().divide(sellRate.getRate(),BigDecimal.ROUND_HALF_DOWN).setScale(5, RoundingMode.HALF_DOWN);
        }

        if(buyRate.getRate().compareTo(sellRate.getRate()) < 0){
            result = sellRate.getRate().divide(buyRate.getRate(),BigDecimal.ROUND_HALF_DOWN).setScale(5, RoundingMode.HALF_DOWN);
        }

        System.out.println(result);

        return new BaseResult<>(BaseStatus.SUCCESS.getCode(),result);
    }

    @RequestMapping(value = "/checkRate")
    public BaseResult<String> checkRate(@RequestParam("costRate") String costRate,@RequestParam("acceptedBooKRate") String acceptedBooKRate){
       //获取CONTRACT_COST_RATE_TOLER参数计算预定汇率范围是否合理
        List<SystemParam> params = systemParamService.getSystemParamList("CONTRACT_COST_RATE_TOLER", "DEC");
        if(params.isEmpty()){
            return new BaseResult<>(BaseStatus.SYSTEM_PARAM_DATA_NOT_EXIST.getCode(),BaseStatus.SYSTEM_PARAM_DATA_NOT_EXIST.getDesc());
        }

        return rateService.checkAcceptedRate(new BigDecimal(costRate),new BigDecimal(acceptedBooKRate),params.get(0));
    }

    @GetMapping(value = "/updateRate")
    public BaseResult<String> updateRate(){
        String result1 =null;
        String url ="http://web.juhe.cn/finance/exchange/frate";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("key",rateService.APPKEY);//APP Key
        params.put("type","");//两种格式(0或者1,默认为0)

        try {
            result1 =rateService.net(url, params, "GET");

            //将字符串转化成JSON对象
            JSONObject object = JSONObject.parseObject(result1);
            //转化成JSON数组
            JSONArray resultList = object.getJSONArray("result");

            JSONObject json = (JSONObject) resultList.get(0);

            Integer latestRate = rateService.getLatestRate(json);

            if(latestRate >= 1){
                logger.info("update Latest Rate");
                return new BaseResult<>(BaseStatus.UPDATE_RATE_SUCCESS.getCode(),BaseStatus.UPDATE_RATE_SUCCESS.getDesc());
            }else {
                logger.info("no date update Latest Rate");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new BaseResult<>(BaseStatus.NO_RATE_DATA_UPDATE.getCode(),BaseStatus.NO_RATE_DATA_UPDATE.getDesc());
    }

}
